<?php

/**
 * @Author: jack
 * @Date:   2024-07-04 10:10:56
 * @Last Modified by:   jack
 * @Last Modified time: 2025-08-07 15:40:08
 */
namespace App\Admin\Metrics\Home;


use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\ApexCharts\Chart as AChart;
use App\Models\User as MUser;
use App\Models\UserBingshi;
use App\Models\UserDangan;
use App\Admin\Repositories\Config;

class User extends AChart
{
    protected $data = [];
    public function __construct($containerSelector = null, $options = [])
    {
        parent::__construct($containerSelector, $options);
        // $this->data = $containerSelector;
        
// dd($containerSelector);
        $this->setUpOptions();
    }

    /**
     * 初始化图表配置
     */
    protected function setUpOptions()
    {
        $color = Admin::color();

        $colors = [$color->primary(), $color->yellow(),$color->success(), $color->warning(),$color->tear()];

        $this->options([
            'colors' => $colors,
            'chart' => [
                'type' => 'bar',
                'height' => 450,
                'background'=> '#fff'
            ],
            'xaxis' => [
                'categories' => []
            ],
            'title' => [
                'text'=> '近7天内数量',
                'align'=> 'center',
                'floating'=> true
            ]
        ]);
    }

    /**
     * 处理图表数据
     */
    protected function buildData()
    {
        $date = [];
        for($i = 0;$i<7;$i++){
            $date[] = date('Y-m-d', strtotime("-$i day"));
        }
        $categories = array_reverse($date);
        $num = [];
        foreach ($date as $val) {
            $num[] = UserBingshi::whereDate('created_at', $val)->count();   
        }
        $data[] = [
            'data' => array_reverse($num),
            'name' => '初诊'
        ];
        $num = [];
        foreach ($date as $val) {
            $num[] = MUser::whereDate('created_at', $val)->count();  
        }
        $data[] = [
            'data' => array_reverse($num),
            'name' => '复诊'
        ];

        
        // dd($date);
        
        $this->withData($data);
        $this->withCategories($categories);
    }

    
    /**
     * 设置图表数据
     *
     * @param array $data
     *
     * @return $this
     */
    public function withData(array $data)
    {
        return $this->option('series', $data);
    }

    /**
     * 设置图表类别.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withCategories(array $data)
    {
        return $this->option('xaxis.categories', $data);
    }

    /**
     * 渲染图表
     *
     * @return string
     */
    public function render()
    {
        $this->buildData();

        return parent::render();
    }
}
